package com.cjlgb.design.common.core.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.SneakyThrows;

/**
 * @author Bin
 * @date 2018/12/24 15:54
 * description: JSON 工具类
 */
public class JsonUtils {

    private final static ObjectMapper MAPPER = new ObjectMapper();

    static {
        //  忽略value为null时，key的输出
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //  禁用对日期以时间戳方式输出的特性
        MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        MAPPER.registerModule(new JavaTimeModule());
        /*
            序列换成json时,将所有的long变成string
            因为js中得数字类型不能包含所有的java long值
         */
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, ToStringSerializer.instance);
        module.addSerializer(Long.TYPE, ToStringSerializer.instance);
        MAPPER.registerModule(module);
    }

    @SneakyThrows
    public static String toJson(Object obj) {
        return MAPPER.writeValueAsString(obj);
    }

    @SneakyThrows
    public static <T> T toBean(String json, Class<T> cls) {
        return MAPPER.readValue(json, cls);
    }

    @SneakyThrows
    public static JsonNode readTree(byte[] bytes){
        return MAPPER.readTree(bytes);
    }

}
